package com.android.interfata;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.menu.MenuAbout;
import com.android.menu.MenuContact;
import com.android.menu.MenuHelp;
import com.android.menu.MenuLegal;

public class Scan extends Activity
{
	private static final String TAG = "Barcode" ;
	String contents, format;
	
	public String[] categories = { "", "", "", "", "Books", "Multimedia", "Music", "", "Movies", 
			"Electronics", "Computers", "Cameras", "Ebooks", "Software"};

	private String pozaDefault = "http://mail.pioneerinvestments.ro:333/images/img.jpg";
	
	public String title;
	public String detail;	
	public String imgid; 	
	public Double rating, price;	
	public String authors, brand;	
	public Long id;	
	public String imageLarge;	
	public String linkAmazon, linkEbay; 
	
	private int numResults;
	private String succes;
	private String mesaj;
	
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);		
		setContentView(R.layout.scan);
		
		addInfo();
		
		ImageView scanIV = (ImageView) findViewById(R.id.scanIV);
		scanIV.setOnClickListener(new View.OnClickListener()
        {
			public void onClick(View v) 
			{
				Log.d(TAG, "onClick din BarcodeActivity");
				Intent intent = new Intent("com.google.zxing.client.android.SCAN");
				startActivityForResult(intent, 0);
				Log.d(TAG, "la sf in onClick din BarcodeActivity");
				
			}
		});
		
		
		/*
		Button scan = (Button) findViewById(R.id.scan);
        scan.setOnClickListener(new View.OnClickListener()
        {
			public void onClick(View v) 
			{
				Log.d(TAG, "onClick din BarcodeActivity");
				Intent intent = new Intent("com.google.zxing.client.android.SCAN");
				startActivityForResult(intent, 0);
				Log.d(TAG, "la sf in onClick din BarcodeActivity");
				
				
			}
		});*/
	}	

	public void onActivityResult(int requestCode, int resultCode, Intent intent) 
	{
		 Log.d(TAG, "la inceput in onActivityResult din BarcodeActivity");
		   if (requestCode == 0)
		   {
			  Log.d(TAG, "onActivityResult din BarcodeActivity");
		      if (resultCode == RESULT_OK)
		      { 
		    	 /*iau codul */
		         contents = intent.getStringExtra("SCAN_RESULT");
		         format = intent.getStringExtra("SCAN_RESULT_FORMAT");
		         Log.d(TAG, "inainte de handle");
		         
		         
		         
		         
		         if (isBarcode (contents) == 1)
		        	 getProduct(contents);
		         else
		         {
		        	 contents = replace(contents, " ", "%20");
		        	 
		        	 Intent intent1 = new Intent(getApplicationContext(), SearchList.class);
					 intent1.putExtra("searchText", contents);
					 startActivity(intent1);
		         }
		         
		         /*// Handle successful scan
		         Context context = getApplicationContext();
		         CharSequence text = contents + " " + format;
		         int duration = Toast.LENGTH_LONG;
		         
		         Toast toast = Toast.makeText(context, text, duration);
		         toast.show();

		         Log.d(TAG, "la sf onActivityResult");
		*/
		         
		      }
		      else if (resultCode == RESULT_CANCELED)
		      {
		         // Handle cancel
		      }
		   }
	}
	

    // inlocuiesc spatiile
	static String replace(String str, String pattern, String replace)
	{
		String str1;
		int i = 0;
		while (i < str.length())
		{
			
			if ( str.charAt(i) == ' '  && str.charAt(i+1) == ' ')
			{
				str1 = str.substring(0, i) + str.substring(i + 2, str.length());
				str = str1;
			}
			else
				i++;
		}	
		
	    int s = 0;
	    int e = 0;
	    StringBuffer result = new StringBuffer();

	    while ((e = str.indexOf(pattern, s)) >= 0)
	    {
	        result.append(str.substring(s, e));
	        result.append(replace);
	        s = e+pattern.length();
	    }
	    result.append(str.substring(s));
	    return result.toString();
	}
	
	private int isBarcode (String cod)
	{
		int i;
		for (i = 0; i < cod.length(); i++)
			if ( !Character.isDigit(cod.charAt(i)) )
				return 0;
		return 1;
	}
	
	// iau produsul corespunzator codului
	private void getProduct (String cod)
	{
		AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);
		
		try 
        {
	         String xml = XMLfunctions.getXML("GetProdusByUPC?ProdusUPC=" + contents);
	    	 Log.d("xml", xml);
	    	 
	    	 Document doc = XMLfunctions.XMLfromString(xml);	    		
	    	 numResults = XMLfunctions.numResults(doc, "name");
	    	 Log.d("num", numResults + " ");
	    	 
	    	 if (numResults != 1) // trebuie sa fie exact un produs
	    	 {
				
	    		 NodeList nodes = doc.getElementsByTagName("Mesaj");
		         Element e = (Element)nodes.item(0);
		         succes = XMLfunctions.getValue(e, "Success");
		         mesaj = XMLfunctions.getValue(e, "Mesaj");
		         
		         dlgAlert.setMessage(mesaj);
		         dlgAlert.setTitle("Error");
		         dlgAlert.setPositiveButton("OK", null);
		         dlgAlert.setCancelable(true);
		         dlgAlert.create().show();		
	    	 }
	    	 else
	    	 {

		        
				NodeList nodes = doc.getElementsByTagName("TipProdus");
				Element e = (Element)nodes.item(0);
				    
				title = XMLfunctions.getValue(e, "name");
				detail = categories[Integer.parseInt(XMLfunctions.getValue(e, "categ_id"))];
							
				if (XMLfunctions.getValue(e, "imageSmall") == "")
					imgid = pozaDefault;
				else
					imgid = XMLfunctions.getValue(e, "imageSmall");
				
				rating = Double.parseDouble(XMLfunctions.getValue(e, "Rating"));
				price = Double.parseDouble(XMLfunctions.getValue(e, "Price"));
				
				id =  Long.parseLong(XMLfunctions.getValue(e, "ID"));
				brand =  XMLfunctions.getValue(e, "brand");
				authors =  XMLfunctions.getValue(e, "authors");
				
				imageLarge =  XMLfunctions.getValue(e, "imageLarge");
				
				//Linkuri catre ebay Amazon
				
				linkAmazon =  XMLfunctions.getValue(e, "linkAmazon");
				linkEbay =  XMLfunctions.getValue(e, "linkEbay");
				

				
				Intent intent = new Intent(getApplicationContext(), Product1.class);


				intent.putExtra("product", title);
				intent.putExtra("category", detail);
				intent.putExtra("rating", rating);
				intent.putExtra("price", price);
				intent.putExtra("authors", authors);
				intent.putExtra("linkAmazon", linkAmazon);
				intent.putExtra("linkEbay", linkEbay);
				intent.putExtra("id", id);
				intent.putExtra("brand", brand);
				intent.putExtra("imageLarge", imageLarge);
				startActivity(intent);
	    	 }
        }
	   	catch (Exception exc)
	   	{
	   		Log.e("CErr", "eroare in GetProductByUPC " + exc.getMessage() + " " + exc.getLocalizedMessage());
	   	}
	}
	
	//completez campurile cu informatiile corespunzatoare
	private void addInfo()
	{
		// username din header
        TextView user = (TextView) findViewById(R.id.userHeader);
        SharedPreferences logPref = getSharedPreferences("LoginPref", MODE_PRIVATE);
    	String username = logPref.getString("user", "username");
    	user.setText(username);
		
    	// pun informatie in primul textView
    	TextView info1 = (TextView) findViewById(R.id.scanInfo1);
    	info1.setText(Html.fromHtml(getString(R.string.scanInfoText1)));
    	TextView info2 = (TextView) findViewById(R.id.scanInfo2);
    	info2.setText(Html.fromHtml(getString(R.string.scanInfoText2)));
	}


	/*     menu      */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	Intent intent;
        switch (item.getItemId()) 
        {
            case R.id.menu_about:     
            	intent = new Intent(getApplicationContext(), MenuAbout.class);
				startActivity(intent);
                break;
            case R.id.menu_help:     
            	intent = new Intent(getApplicationContext(), MenuHelp.class);
				startActivity(intent);
                break;
            case R.id.menu_legal: 
            	intent = new Intent(getApplicationContext(), MenuLegal.class);
				startActivity(intent);
            	break;
            case R.id.menu_contact:
            	intent = new Intent(getApplicationContext(), MenuContact.class);
				startActivity(intent);
            	break;
        }
        return true;
    }
	/*     end menu      */
}
